package Core

import (
	"html/template"
	"io/ioutil"
	"path"
)

// declare HxTemplate struct
// only work in behavior execution
type HxTemplate struct {
	behavior *HxBehavior
	funcs   template.FuncMap
	viewData map[string]interface {}
}

// Assign view data
func (this *HxTemplate) Assign(key string, value interface {}) *HxTemplate {
	this.viewData[key] = value
	return this
}

// Assign and share view data
// share to global
func (this *HxTemplate) Share(key string, value interface {}) *HxTemplate {
	this.Assign(key, value)
	this.behavior.viewData[key] = value
	return this
}

// Add template func
func (this *HxTemplate) Func(key string, fn interface {}) *HxTemplate {
	this.funcs[key] = fn
	return this
}

// Add and share template func
func (this *HxTemplate) ShareFunc(key string, fn interface {}) *HxTemplate {
	this.Func(key, fn)
	this.behavior.funcMap[key] = fn
	return this
}

// Add css file to global
func (this *HxTemplate) Css(file string) *HxTemplate {
	this.behavior.cssFiles[file] = path.Join(this.behavior.theme, file)
	return this
}

// Add js file to global
func (this *HxTemplate) Js(file string) *HxTemplate {
	this.behavior.jsFiles[file] = path.Join(this.behavior.theme, file)
	return this
}

// Render file with inner data and funcs
func (this *HxTemplate) Render(fileName string) string {
	bytes, e := ioutil.ReadFile(path.Join(this.behavior.theme, fileName))
	if e != nil {
		panic(e)
	}
	return Render(path.Base(fileName), string(bytes), this.viewData, this.funcs)
}

// Append a template file into behavior templates
func (this *HxTemplate) With(theme string, file string) *HxTemplate {
	this.behavior.behaviorTpl = append(this.behavior.behaviorTpl, ThemeFile(theme, file))
	return this
}


